package com.example.layui.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.layui.pojo.Product;
import com.example.layui.mapper.ProductDao;
import com.example.layui.service.ProductService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ProductController {
    @Autowired
    ProductService productService;
    @Autowired
    ProductDao productDao;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/shop/product/list")
    @ResponseBody
    public JSONObject productList(int page, int limit,String productName){
        FieldSortBuilder sort = SortBuilders.fieldSort("productPrice").order(SortOrder.DESC);
        PageRequest pageable=new PageRequest(page-1,limit);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //将搜索条件设置到构建中
        if(productName!=null && !productName.equals("")){
            QueryBuilder queryBuilder = QueryBuilders.matchQuery("productName", productName);
            nativeSearchQueryBuilder.withQuery(queryBuilder);
        }
        //将分页设置到构建中
        nativeSearchQueryBuilder.withPageable(pageable);
        //将排序设置到构建中
        nativeSearchQueryBuilder.withSort(sort);
        //生产NativeSearchQuery
        NativeSearchQuery query = nativeSearchQueryBuilder.build();
        Page<Product> pageObj = productDao.search(query);
        int total = (int) pageObj.getTotalElements();
        List<Product> products = pageObj.getContent();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data",products);
        jsonObject.put("code",0);
        jsonObject.put("msg","");
        jsonObject.put("count",total);
        return jsonObject;
    }

    //导入数据到es redis
    @RequestMapping("/imports")
    public void imports(){
        List<Product> products=productService.getAllProduct();
        for (Product product : products){
            //将数据存入es
            productDao.save(product);
            //id为key   保存库存到redis
            stringRedisTemplate.opsForValue().set(String.valueOf(product.getId()),String.valueOf(product.getProductStack()));
        }
    }

}
